package com.delivery.www.dao.DaoImpl;

import com.delivery.www.dao.CommentDao;
import com.delivery.www.po.Comment;
import com.delivery.www.util.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommentDaoImpl implements CommentDao {
    @Override
    public int doComment(int storeId, int userId, String content) {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        Object[] params = {storeId, userId, content};
        String sql = "insert into comment (store_id,user_id,content) values(?,?,?)";
        int excute = JdbcUtils.excute(connection, pstm, sql, params);
        if (excute > 0) {
            Object[] objects = {storeId};
            String s = "update store set comment_num = comment_num + 1 where store_id = ?";
            JdbcUtils.excute(connection, pstm, s, objects);
        }
        JdbcUtils.closeResource(connection, pstm, null);
        return excute;
    }

    @Override
    public List<Comment> getComment(int storeId) {
        Connection connection = JdbcUtils.getConnection();
        List<Comment> comments = new ArrayList<>();
        PreparedStatement pstm = null;
        ResultSet rs = null;
        Object[] params = {storeId};
        String sql = "select c.comment_id,content,u.user_name from comment c inner join user u on u.user_id = c.user_id where c.store_id = ?";
        rs = JdbcUtils.excute(connection, pstm, rs, sql, params);
        try {
            while (rs.next()) {
                Comment comment = new Comment();
                comment.setCommentId(rs.getInt("comment_id"));
                comment.setContent(rs.getString("content"));
                comment.setUserName(rs.getString("user_name"));
                comments.add(comment);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        JdbcUtils.closeResource(connection, pstm, rs);
        return comments;
    }

    @Override
    public int deleteComment(int commentId, int storeId) {
        Connection connection = JdbcUtils.getConnection();
        PreparedStatement pstm = null;
        Object[] params = {commentId};
        String sql = "delete from comment where comment_id = ?";
        int excute = JdbcUtils.excute(connection, pstm, sql, params);
        if (excute > 0) {
            Object[] objects = {storeId};
            String s = "update store set comment_num = comment_num - 1 where store_id = ?";
            JdbcUtils.excute(connection, pstm, s, objects);
        }
        JdbcUtils.closeResource(connection, pstm, null);
        return excute;
    }
}
